package com.bjpowernode.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.shop.base.BaseProduct;
import com.bjpowernode.shop.constants.CommonConstants;
import com.bjpowernode.shop.domain.Category;
import com.bjpowernode.shop.domain.ProdTag;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/prod/category")
public class ProdCategoryController extends BaseProduct {

    // 查询产品分类列表
    @GetMapping("/table")
    public ResponseEntity<List<Category>> table() {
        return ResponseEntity.ok(categoryService.list(
                new LambdaQueryWrapper<Category>()
                        // 只显示启用状态的
                        .eq(Category::getStatus, 1)
                        // 按seq排序
                        .orderByAsc(Category::getSeq)
        ));
    }

    // 列出产品一级分类 【选项里只能选一级分类新增为二级分类，或不选分类新增为一级分类】
    @GetMapping("/listCategory")
    public ResponseEntity<List<Category>> listCategory() {
        return ResponseEntity.ok(categoryService.list(
                new LambdaQueryWrapper<Category>()
                        // 只显示启用状态的
                        .eq(Category::getStatus, 1)
                        // 按seq排序
                        .orderByAsc(Category::getSeq)
                        // 只查父分类
                        .eq(Category::getParentId, 0)
        ));
    }

    // 新增产品分类
    @PostMapping
    public ResponseEntity<Boolean> saveCategory(@RequestBody Category category) {
        return ResponseEntity.ok(categoryService.save(category
                .setShopId(CommonConstants.DEFAULT_SHOP_ID)
                .setRecTime(new Date())
                // 分类级别，parentId为0则一级，否则二级
                .setGrade(
                        category.getParentId().equals(0L) ? 1 : 2
                )));
    }

    // 查询当前要修改的分类
    @GetMapping("/info/{id}")
    public ResponseEntity<Category> getCategory(@PathVariable Integer id) {
        return ResponseEntity.ok(categoryService.getById(id));
    }

    // 修改分类
    @PutMapping
    @Transactional
    public ResponseEntity<Boolean> updateCategory(@RequestBody Category category) {
        return ResponseEntity.ok(categoryService.saveOrUpdate(category
                .setGrade(category.getParentId().equals(0L) ? 1 : 2)
                .setUpdateTime(new Date())
        ));
    }

    // 删除分类
    @DeleteMapping("/{id}")
    @Transactional
    public ResponseEntity<Boolean> delCategory(@PathVariable Integer id) {
        return ResponseEntity.ok(categoryService.removeById(id));
    }
}
